<template>
  <div >
    <el-container>
      <el-header
        style="display:flex;align-items: center;justify-content: space-between;padding: 10px;border-bottom: 1px solid #f2f2f2;">
        <div>
          <svg-icon class="primary" :icon-class="$route.meta.icon"/>
          <span class="primary">{{companyForm.name}}员工导入</span>
        </div>
      </el-header>
      <div class="pd10">
          <div style="align-items: center;margin: 10px; margin-left: 20px" >
              <el-row :gutter="24" style="margin-bottom: 10px">
                <div style="line-height:1.8;font-size:20px" >上传充值表</div>
                <div style="line-height:1.5;font-size:16px">充值表说明</div>
                <div style="line-height:1.2;font-size:14px">1.充值表有企业提供，勿擅自调整。因擅自调整带来的充值问题，需承担相应的损失；</div>
                <div style="line-height:1.2;font-size:14px">2.若企业提供多个充值标，请上传全部列表后统一充值，一个列表有且仅有一种福利类型；</div>
                <div style="line-height:1.2;font-size:14px">3.若手动为企业填写填写充值表，请点击下载模板</div>
                <div style="line-height:1.2;font-size:14px">4.提交充值后的名单不可撤回，需要通过正负金额充值调整</div>
              </el-row>
              <el-row :gutter="24" style="margin-bottom: 10px">
                <ExportList2Excel ref="exportList2Excel" @handleExport="handleExport" name="下载充值模板" />
                <el-popover
                placement="bottom"
                title="温馨提示"
                width="200"
                trigger="manual"
                :content="popoverContent"
                v-model="popoverVisible"
                >
                <el-button
                    style="margin-left: 10px"
                    icon="el-icon-refresh-right"
                    type="info"
                    @click="daoruClick"
                    slot="reference"
                >上传充值表格</el-button>
                </el-popover>
              </el-row>
                <el-row :gutter="24" >
                    <el-form :model="rechargeForm" :rules="rules" ref="rechargeForm" label-width="0px" class="demo-form-inline" :inline="true">
                        <el-form-item prop="memo">
                            <el-input
                                placeholder="福利名称"
                                style="width: 200px"
                                v-model="rechargeForm.memo"
                            ></el-input>
                        </el-form-item>
                        <el-form-item prop="daterangeValue">
                            <el-date-picker v-model="rechargeForm.daterangeValue" type="daterange" range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期" :picker-options="pickerOptions">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item prop="tags">
                            <el-select v-model="rechargeForm.selectTags" style="width: 100%" clearable multiple filterable placeholder="输入标签名搜索">
                                <el-option
                                v-for="item in tagOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </el-row>
            </div>
        <el-table
          :data="memberData"
          border
          stripe
          ref="table"
          style="width: 100%;">
          <!-- <el-table-column label="企业名称" align="center" prop="companyName" width="100"></el-table-column>
          <el-table-column label="福利名称" align="center" prop="memo"></el-table-column> -->
          <el-table-column label="卡号" align="center" prop="code" width="200"></el-table-column>
          <el-table-column label="手机号码" align="center" prop="mobile" width="200"></el-table-column>
          <el-table-column label="员工名称" align="center" prop="name" width="200"></el-table-column>
          <el-table-column label="充值金额" align="center" prop="amount" width="200"></el-table-column>
          <el-table-column label="错误提示" align="center" prop="errorMsg"></el-table-column>
        </el-table>
      </div>
      <el-footer class="el-footerBox">
        <el-row :gutter="24" style="margin-bottom: 10px">
          <el-button
            style="margin-left: 10px"
            icon="el-icon-refresh-right"
            type="info"
            :loading="checked"
            @click="updateClick"
          >确认充值</el-button>
        </el-row>
      </el-footer>
      <upload-excel-component
        ref="upload"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
      />

        <el-dialog
            title="提示"
            :visible.sync="centerDialogVisible"
            width="30%"
            center>
            <p><b id="DialogMsg" >{{rechargeForm.memo}}</b> 的福利卡充值总金额：<b id="DialogMsg">{{dialogAmount}}</b>元，充值总人数： <b id="DialogMsg">{{dialogNum}}</b>人，有限期：<b id="DialogMsg">{{dialogDaterange}}</b>，信息确认完成，请点击下方的确认充值</p>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
    </el-container>
  </div>
</template>

<script>
    import permission from '@/directive/permission/index.js' // 权限判断指令
    import {uploadChargeMoney} from '@/api/cardBill'
    import {list} from '@/api/tag'
    import utils from '../../utils/utils.js'
    import {EventBus} from '@/api/eventBus'
    import Pagination from '@/components/Pagination';
    import CategoryPanel from '@/components/CategoryPanel'
    import UploadExcelComponent from "@/components/UploadExcel/index.vue";
    import ExportList2Excel from "@/components/ExportList2Excel";

  export default {
    name: 'employee-list',
    directives: { permission },
    data() {
      return {
        memberData: [],
        pageNum: 1,
        pageSize: 20,
        total: 0,
        queryType: true,
        query: {
          name: '',
          phone: '',
          vip:""
        },
        keyword: {
          name: '',
          phone: ''
        },
        queryPhone: '',
        queryName: '',
        curHeight: null,
        excelData: [],
        memberCategoryId: '',
        deleted: false,
        restoreForm: {
          id: '',
          deleted: false,
        },
        companyForm:{
          id:"",
          name:"",
        },
        popoverVisible: false, //导入检验成功后的弹窗提示
        popoverContent: "", //弹窗提示的内容
        checked: false, //防止双击
        checkTableDataLock: false, //表格数据检验的锁，前端检验成功后解锁
        memo:"", //福利名称
        daterangeValue:"",//有效期
        rechargeForm:{memo:"",daterangeValue:"",selectTags:[]},
        rules: {
            memo: [
                { required: true, message: '请输入福利名称', trigger: 'blur' }
            ],
            daterangeValue: [
                { required: true, message: '请选择有效期时间段', trigger: 'blur' }
            ]
        },
        pickerOptions:{
            disabledDate(time) {
            return time.getTime() < (Date.now()-86400000);
          },
        },
        centerDialogVisible:false,
        dialogAmount: 0,
        dialogNum:0,
        dialogDaterange:"",

        tagOptions:[
            {
                value: '',
                label: ''
            }
        ]
      }
    },

    components: {Pagination, CategoryPanel,UploadExcelComponent, ExportList2Excel},
    created() {
      var _this = this
      _this.companyForm.id = this.$route.query.companyId;
      _this.companyForm.name = this.$route.query.companyName;
      console.info("_this.companyId--"+ Date.now())
      this.getTagData()
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    methods: {

        //获取福利卡的标签数据
        getTagData(){
            list({type:3})
                .then(response => {
                        console.log("名单导入的回复信息"+JSON.stringify(response) )
                        let tagOptions = []
                        if(response.type == "success"){
                            if(response.data.data.length > 0){
                                response.data.data.map(item=>{
                                    let tagOptionsItem = {}
                                    tagOptionsItem.label = item.name
                                    tagOptionsItem.value = item.id
                                    tagOptions.push(tagOptionsItem)
                                })
                            }
                            this.tagOptions = tagOptions
                        }
                })
                .catch(error => {
                    console.log("error!!");
                });
        },

        //表格数据校验
        checkTableData(_this, data, origenalData) {
            let errorTableDate = [];
            let mobileList = []
            if (data.length > 0) {
                data.map((item, index) => {
                let lock = false;
                if (item.mobile == "" && item.code == '') {
                  lock = true;
                  this.$message('请输入手机号或者卡号')
                  origenalData[index].errorMsg += "请输入手机号或者卡号，";
                }else if(item.mobile != ''){
                  if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(item.mobile)) {
                    lock = true;
                    origenalData[index].errorMsg += "手机号码输入有误，";
                  }else if(mobileList.indexOf(item.mobile) > -1 ){
                    lock = true;
                    origenalData[index].errorMsg += "手机号码存在重复，";
                  }else if(mobileList.indexOf(item.mobile)  == -1 ){
                    mobileList.push(item.mobile)
                  }
                }
                if (item.code == '' && item.name == "") {
                    lock = true;
                    origenalData[index].errorMsg += "员工名称不能为空，";
                }
                if (item.amount == "") {
                    lock = true;
                    origenalData[index].errorMsg += "充值金额不能为空，";
                }else if (!/^(\-|[1-9][0-9]*)+(.[0-9]{1,2})?$/.test(item.amount)) {
                    lock = true;
                    origenalData[index].errorMsg += "充值金额输入有误，";
                }


                if (lock) {
                    _this.checkTableDataLock = false;
                    errorTableDate.push(origenalData[index]);
                }
                });
                if (errorTableDate.length == 0) {
                _this.checkTableDataLock = true;
                }else if(errorTableDate.length > 0){
                    errorTableDate.map((item)=>{
                        item.errorMsg = item.errorMsg.substr(0, item.errorMsg.length-1)
                    })
                }
            }
            return errorTableDate;
        },

        //名单导入
        beforeUpload(file) {
            const isLt1M = file.size / 1024 / 1024 < 1;
            if (isLt1M) {
                return true;
            }
            this.$message({
                message: "Please do not upload files larger than 1m in size.",
                type: "warning"
            });
            return false;
        },

        //导入表单成功回调事件
        handleSuccess({ results, header, firstSheetName }) {
            let _this = this;
            let matchInfo = [
                { label: "卡号", value: "code" },
                { label: "手机号码", value: "mobile" },
                { label: "员工名称", value: "name" },
                { label: "充值金额", value: "amount" },
            ];
            _this.memberData = [];
            console.log("获取的导入结果results--" + JSON.stringify(results));
            let matchResults = [];
            let origenalResult = [];
            if (results.length > 0) {
                results.map(item => {
                let matchResultsItem = {};
                let origenalResultItem = {};
                origenalResultItem.errorMsg = "";
                matchInfo.map(matchInfoItem => {
                    if (item[matchInfoItem.label]) {
                    matchResultsItem[matchInfoItem.value] = item[matchInfoItem.label];
                    origenalResultItem[matchInfoItem.value] =
                        item[matchInfoItem.label];
                    } else {
                    matchResultsItem[matchInfoItem.value] = "";
                    origenalResultItem[matchInfoItem.value] = "";
                    }
                });
                matchResults.push(matchResultsItem);
                origenalResult.push(origenalResultItem);
                });
            }
            origenalResult = _this.checkTableData(
                _this,
                matchResults,
                origenalResult
            );
            //   console.info("_this.checkTableDataLock--"+_this.checkTableDataLock)
            if (_this.checkTableDataLock == false) {
                _this.memberData = origenalResult;
            } else {
                let dialogAmount = 0
                if(matchResults.length > 0){
                    matchResults.map(item =>{
                        dialogAmount += item.amount
                    })
                }
                this.$refs['rechargeForm'].validate((valid) => {
                if (valid) {
                    _this.dialogName = this.rechargeForm.memo
                _this.dialogAmount = dialogAmount
                _this.dialogNum = matchResults.length;
                let startDate = this.rechargeForm.daterangeValue[0].getFullYear()+"-"+(this.rechargeForm.daterangeValue[0].getMonth()+1)+"-"+this.rechargeForm.daterangeValue[0].getDate()
                let endDate = this.rechargeForm.daterangeValue[1].getFullYear()+"-"+(this.rechargeForm.daterangeValue[1].getMonth()+1)+"-"+this.rechargeForm.daterangeValue[1].getDate()
                _this.dialogDaterange = startDate + " 至 " +  endDate
                _this.centerDialogVisible = true;
                this.firstSheetName = firstSheetName;
                this.daoruData = matchResults;
                this.daoruType = true;
                }
                })

            }

            console.log(
                "获取的导入结果matchResults--" + JSON.stringify(matchResults)
            );
            console.log(
                "获取的导入结果origenalResult--" + JSON.stringify(origenalResult)
            );

            // console.log("获取的表头信息header--" + header)
            // console.log("获取的表头信息firstSheetName--" + firstSheetName)

        },

        //上传表格数据点击事件
        daoruClick() {
            this.$refs.upload.handleUpload();
        },

        //下载模板的函数
        handleExport() {
            var _this = this;
            console.info("福利名称--"+this.rechargeForm.memo)
            console.info("福利名称--"+this.rechargeForm.daterangeValue)

            //要导出函数携带的参数
            let data = {};
            console.log("下载模板的函数this.companyForm.name--" + JSON.stringify(this.companyForm.name));
            data.tHeader = ["卡号","手机号码", "员工名称", "充值金额"];
            data.filterVal = ["code","mobile", "name", "amount"];
            data.filename = this.companyForm.name + "福利充值导入模板";
            let day = new Date()
            let startTime = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" +  day.getDate()
            let nextday = new Date(day.setDate(day.getDate() + 1))
            let endTime = nextday.getFullYear() + "-" + (nextday.getMonth() + 1) + "-" +  nextday.getDate()
            data.list = [
                {
                code:888888888888,
                mobile: 18888888888,
                name: "张三",
                amount: 200,
                }
            ];
            _this.$refs.exportList2Excel.handleDownload(data);
        },

        //确认上传的服务器请求事件
        updateClick() {
            this.$refs['rechargeForm'].validate((valid) => {
                if (valid) {
                    let _this = this;
                    console.info("发送服务器的请求被调用了this.daoruData--"+JSON.stringify(_this.rechargeForm));
            if (this.checkTableDataLock) {
                this.popoverVisible = false;
                this.checked = true;

                console.info("发送服务器的请求被调用了this.companyForm.id--"+this.companyForm.id);
                console.info("发送服务器的请求被调用了this.daoruData--"+JSON.stringify(this.daoruData));
                let idInfo = {
                    cardType:1,
                    companyId:_this.companyForm.id,
                    memo:_this.rechargeForm.memo,
                    startDate:this.rechargeForm.daterangeValue[0].getFullYear()+"-"+(this.rechargeForm.daterangeValue[0].getMonth()+1)+"-"+this.rechargeForm.daterangeValue[0].getDate(),
                    endDate:this.rechargeForm.daterangeValue[1].getFullYear()+"-"+(this.rechargeForm.daterangeValue[1].getMonth()+1)+"-"+this.rechargeForm.daterangeValue[1].getDate(),
                    tagIds:_this.rechargeForm.selectTags.join(",")
                }
                console.log("福利卡创建导入的回复信息idInfo--"+JSON.stringify(idInfo) )
                console.log(this.daoruData)
                uploadChargeMoney(idInfo, this.daoruData)
                .then(response => {
                        this.checked = false;
                        console.log("福利卡创建导入的回复信息"+JSON.stringify(response) )
                        if(response.data.returnCode == "success"){
                            console.log("名单导入的回复信息"+JSON.stringify(response) )
                            _this.rechargeForm.memo = ""
                            this.rechargeForm.daterangeValue = ""

                            EventBus.$emit("recharge", _this.companyForm)
                            _this.$store.dispatch("tagsView/delView", _this.$route).then(({ visitedViews }) => {
                                _this.$router.push({
                                path: "/company/employeeList",
                                query: { id: _this.companyForm.id, companyName: _this.companyForm.companyName }
                                });
                            }); // 关闭当前tab回到列表
                            _this.$message({
                            message: response.content,
                            offset: 120,
                            center: true
                            });
                        }else if(response.data.returnCode == "error"){
                            console.log("名单导入的回复信息"+JSON.stringify(response) )
                            this.checkTableDataLock = false
                            if(response.data.vo.length > 0){
                                console.log("名单导入的回复信息111")
                                response.data.vo.map((item)=>{
                                    item.errorMsg = item.result
                                })
                            }
                            _this.memberData = response.data.vo
                            console.log("名单导入的回复信息_this.memberData"+JSON.stringify(_this.memberData) )
                        }

                })
                .catch(error => {
                    console.log("error!!");
                    this.checked = false;
                });
            }else{
                _this.$message({
                            message: "请先导入表格",
                            offset: 120,
                            center: true
                            });
            }
                }else{

                }
            })

        },

        //查询的确认点击事件
        queryClick() {
            this.keyword = this.query;
            this.pageNum = 1;
        },

        //查询的重置点击事件
        resetClick() {
            this.query.phone = "";
            this.query.name = "";
            this.keyword = this.query;
            this.pageNum = 1;
        },

        beforeMount() {
            window.onresize = () => {
            return (() => {
                if (this.queryType == false) {
                var h = document.documentElement.clientHeight || document.body.clientHeight;
                this.curHeight = h - 266//减去页面上固定高度height
                } else {
                var h = document.documentElement.clientHeight || document.body.clientHeight;
                this.curHeight = h - 220//减去页面上固定高度height
                }
            })();
            };
        },

        comeIn(){
            console.log('222')
            var h = document.documentElement.clientHeight || document.body.clientHeight;
            this.curHeight = h - 220//减去页面上固定高度height
        },


        //查询企业员工的信息
        loadMember(val) {
            console.log("传输过来的企业id"+val)
            var _this = this
            let params = new URLSearchParams();
            params.append('pageNum', _this.pageNum);
            params.append('pageSize', _this.pageSize);
            params.append('phone', _this.keyword.phone);
            params.append('name', _this.keyword.name);
            params.append('vip', _this.keyword.vip);
            params.append('memberCategoryId', _this.memberCategoryId);
            params.append('deleted', _this.deleted);
            list(params).then(response => {
            // console.log("请求的会员信息"+JSON.stringify(response) )
            _this.memberData = response.data.data
            _this.total = response.data.total
            }).catch(error => {
            console.log('error!!')
            });
        },

        chooseClick() {
            this.queryType = !this.queryType
            if (this.queryType == false) {
            var h = document.documentElement.clientHeight || document.body.clientHeight;
            this.curHeight = h - 266//减去页面上固定高度height
            } else {
            var h = document.documentElement.clientHeight || document.body.clientHeight;
            this.curHeight = h - 220//减去页面上固定高度height
            }
        },
    }
  }
</script>

<style scoped>
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #f2f2f2;
  }

  #DialogMsg{
      color: crimson;
  }
</style>
